package com.jinxin.platform.cddjnhjcxtsysset.service.impl;

import com.alibaba.excel.EasyExcel;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cddjnhjcxtsysset.bean.CddjnhjcxtsyssetHomeExpend;
import com.jinxin.platform.cddjnhjcxtsysset.bean.CddjnhjcxtsyssetHomeExpend2;
import com.jinxin.platform.cddjnhjcxtsysset.common.SysOrgInfo;
import com.jinxin.platform.cddjnhjcxtsysset.common.SysUserVO;
import com.jinxin.platform.cddjnhjcxtsysset.mapper.CddjnhjcxtsyssetHomeExpend2Mapper;
import com.jinxin.platform.cddjnhjcxtsysset.mapper.CddjnhjcxtsyssetHomeExpendMapper;
import com.jinxin.platform.cddjnhjcxtsysset.rpc.CddjnhjcxtsyssetRpc;
import com.jinxin.platform.cddjnhjcxtsysset.service.ICddjnhjcxtsyssetHomeExpendService;
import com.jinxin.platform.cddjnhjcxtsysset.utils.ExpendExcel;
import com.jinxin.platform.cddjnhjcxtsysset.utils.ExpendExcelListener;
import com.jinxin.platform.cddjnhjcxtsysset.utils.ExportExcelUtils;
import com.jinxin.platform.cddjnhjcxtsysset.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-07-20
 * @Author: Lingnan
 **/
@Slf4j
@Service
public class CddjnhjcxtsyssetHomeExpendServiceImpl implements ICddjnhjcxtsyssetHomeExpendService {
    @Autowired
    private CddjnhjcxtsyssetHomeExpendMapper homeExpendMapper;
    @Autowired
    private CddjnhjcxtsyssetHomeExpend2Mapper homeExpend2Mapper;
    @Autowired
    private CddjnhjcxtsyssetRpc cddjnhjcxtsyssetRpc;

    @Override
    public CddjnhjcxtsyssetHomeExpend selectOne(HashMap param) {
        return homeExpendMapper.selectOne(param);
    }

    @Override
    public List<CddjnhjcxtsyssetHomeExpend> list(HashMap param) {
        return homeExpendMapper.list(param);
    }

    @Override
    public JsonResult saveOrUpdate(List<CddjnhjcxtsyssetHomeExpend> records) {
        SysUserVO currentUser = cddjnhjcxtsyssetRpc.getCurrentUser();
        if(currentUser == null){
            return JsonResult.error("获取当前用户信息失败");
        }
        if (records == null || records.size() == 0){
            return JsonResult.error("参数错误，操作失败");
        }
        String orgId = currentUser.getOrgId();
        homeExpendMapper.deleteByOrgId(orgId);
        List<CddjnhjcxtsyssetHomeExpend> list = new ArrayList<>();
        records.forEach(record->{
            record.setId(Utils.getUuid());
            record.setOrgId(orgId);
            list.add(record);
        });
        int count = homeExpendMapper.insertBatch(list);
        if(count > 0){
            return JsonResult.ok("保存成功","");
        }else {
            return JsonResult.error("操作失败，请重试");
        }
    }

    @Override
    public JsonResult importExcel(MultipartFile file, String titleMap) {
        try {
            ExpendExcelListener listener = new ExpendExcelListener(homeExpend2Mapper);
            EasyExcel.read(file.getInputStream(), ExpendExcel.class, listener).sheet().doRead();
            if (listener.insertedCount != 0 || listener.updatedCount != 0) {
                return JsonResult.ok(listener.msg,null);
            }else {
                return JsonResult.error(listener.msg);
            }
        } catch (Exception e) {
            return JsonResult.error(e.getMessage());
        }
    }

    @Override
    public JsonResult export2Excel(HttpServletResponse response) {
        SysUserVO currentUser = cddjnhjcxtsyssetRpc.getCurrentUser();
        if (currentUser == null) {
            return JsonResult.error("未登录");
        }
        String orgId = currentUser.getOrgId();
        if(StringUtils.isEmpty(orgId)){
            return JsonResult.error("当前账号无组织");
        }
        HashMap param = new HashMap();
        param.put("orgId",orgId);
        List<CddjnhjcxtsyssetHomeExpend2> list = homeExpend2Mapper.list(param);
        if(list == null || list.size() == 0){
            return JsonResult.error("无数据");
        }
        String fileName = "费用支出表.xls";
        try {
            fileName = new String(fileName.getBytes("GB2312"), "ISO_8859_1");
        } catch (UnsupportedEncodingException e) {
            log.error("error",e);
            return JsonResult.error("导出学生信息字符错误，请联系管理员");
        }
        response.setHeader("Content-Disposition", "attachment; filename=".concat(fileName));
        response.setHeader("Connection", "close");
        response.setHeader("Content-Type", "application/vnd.ms-excel");
        response.setContentType("application/x-download;charset=UTF-8");
        String[] headers = {"序号", "结算年","结算月","电费支出", "水费支出", "热力费支出","天然气支出","汽油支出","柴油支出","液化气支出","组织ID"};
        List<List<String>> resultData = new ArrayList<>();
        int index = 0;
        for (CddjnhjcxtsyssetHomeExpend2 expend : list) {
            List<String> fieldList = new ArrayList<>();
            fieldList.add((++index)+"");
            fieldList.add(expend.getJsyear()+"");
            fieldList.add(expend.getJsmonth()+"");
            fieldList.add(expend.getDfzc()+"");
            fieldList.add(expend.getSfzc()+"");
            fieldList.add(expend.getRlfzc()+"");
            fieldList.add(expend.getTrqzc()+"");
            fieldList.add(expend.getQyzc()+"");
            fieldList.add(expend.getMyzc()+"");
            fieldList.add(expend.getYhqzc()+"");
            fieldList.add(expend.getOrgId()+"");
            resultData.add(fieldList);
        }
        HSSFWorkbook workbook = new HSSFWorkbook();
        OutputStream ouputStream = null;
        try {
            ouputStream = response.getOutputStream();
            ExportExcelUtils.exportExcel(workbook,0,"费用支出",headers,resultData);
            workbook.write(ouputStream);
            String msg = "成功导出"+(list.size())+"条费用支出记录";
            log.info(msg);
            return JsonResult.ok(msg,null);
        } catch (Exception e) {
            log.error("导出费用支出记录出错", e);
            e.printStackTrace();
            return JsonResult.error("导出费用支出记录错误，请重试或联系管理员");
        }finally {
            if(ouputStream != null){
                try {
                    ouputStream.close();
                } catch (IOException e) {
                    log.error("error",e);
                }
            }
        }

    }
}
